import string

from zope.interface import implements
from zope.component import adapter, getMultiAdapter, getUtility

from zope.app.container.interfaces import INameChooser

from plone.portlets.interfaces import IPortletManager
from plone.portlets.interfaces import IPortletAssignmentMapping

from Acquisition import aq_inner, aq_parent

from Products.Archetypes import atapi
from Products.Archetypes.interfaces import IObjectInitializedEvent

from Products.ATContentTypes.content import folder
from Products.ATContentTypes.content.schemata import finalizeATCTSchema

from AccessControl import ClassSecurityInfo
from AccessControl.SecurityManagement import newSecurityManager
from Products.CMFCore import permissions

from apkn.resource.interfaces import IResourceFolder

from apkn.resource.config import *

from apkn.resource import ResourceMessageFactory as _


ResourceFolderSchema = folder.ATFolderSchema.copy() + atapi.Schema((
    atapi.TextField('text',
        required=False,
        searchable=True,
        storage=atapi.AnnotationStorage(),
        validators=('isTidyHtmlWithCleanup',),
        default_output_type='text/x-html-safe',
        widget=atapi.RichWidget(label=_(u"Descriptive text"),
                                description=_(u""),
                                rows=25,
                                allow_file_upload=False),
        ),
    ))


ResourceFolderSchema['title'].storage = atapi.AnnotationStorage()
ResourceFolderSchema['description'].storage = atapi.AnnotationStorage()
    
finalizeATCTSchema(ResourceFolderSchema, folderish=True, moveDiscussion=False)

class ResourceFolder(folder.ATFolder):
    """Contains multiple resources
    """
    implements(IResourceFolder)
    
    portal_type = "Resource Folder"
    
    _at_rename_after_creation = True
    
    schema = ResourceFolderSchema
    
    title = atapi.ATFieldProperty('title')
    description = atapi.ATFieldProperty('description')
    text = atapi.ATFieldProperty('text')
    
    # security settings
    security = ClassSecurityInfo()
    security.declareProtected(permissions.View, 'alphabetise')

    def alphabetise(self):
        items = self.getFolderContents()

        alphabets = {}
        for x in string.uppercase:
            alphabets[x] = []

        for item in items:
            char = item.Title[0].upper()
            if not alphabets.has_key(char):
                continue
            alphabets[char].append(item)

        return [{'letter': x, 'items': alphabets[x]} for x in string.uppercase]
    
    
atapi.registerType(ResourceFolder, PROJECTNAME)
